<template>
  <div class="login-container">
    <el-form :model="loginForm" :rules="rules" ref="loginForm" label-width="80px" class="login-form">
      <h2 class="title">管理员登录</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
        <el-button @click="resetForm('loginForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
        let data = {
            username: this.loginForm.username,
            password: this.loginForm.password,
        }
        // console.log('要发送请求的数据',data)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 调用登录API
          this.$http.post('/admin/login', data).then(res=>{
            // console.log('登录请求结果',res)
            if(res.code === 200){
              
              this.$message.success('登录成功')
              //添加Cookie
              this.$cookies.set('loginUser',res.admin)
              this.$emit('login-success', true);
            }else{
              this.$message.error(res.message)
            }
          })
        //   console.log('登录成功');
        } else {
          console.log('验证失败');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-form {
  width: 400px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
}
.title {
  text-align: center;
  margin-bottom: 20px;
}
</style>